package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("PurchasematerialRestController")
public class PurchasematerialRestController extends CmiEmaController {

	/**
	 * Create a new Purchasematerial entity
	 * 
	 */
	@RequestMapping(value = "/newPurchasematerial", method = RequestMethod.POST)
	@ResponseBody
	public Object newPurchasematerial(@RequestBody Purchasematerial purchasematerial) {
		purchasematerialService.savePurchasematerial(purchasematerial);
		return JSONObject.parse(cmiPsonService
				.toJsonString(purchasematerialDAO.findPurchasematerialByPrimaryKey(purchasematerial.getId()), 2));
	}

	@RequestMapping(value = "/restNewPurchasematerial", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewPurchasematerial(@RequestBody String purchasematerialJson) {
		Purchasematerial purchasematerial = new Gson().fromJson(purchasematerialJson, Purchasematerial.class);
		appendReferences(purchasematerial);
		purchasematerialService.savePurchasematerial(purchasematerial);
		return JSONObject.parse(cmiPsonService
				.toJsonString(purchasematerialDAO.findPurchasematerialByPrimaryKey(purchasematerial.getId()), 2));
	}

	@RequestMapping(value = "/savePurchasematerial", method = RequestMethod.PUT)
	@ResponseBody
	public Purchasematerial savePurchasematerial(@RequestBody Purchasematerial purchasematerial) {
		purchasematerialService.savePurchasematerial(purchasematerial);
		return purchasematerialDAO.findPurchasematerialByPrimaryKey(purchasematerial.getId());
	}

	@RequestMapping(value = "/restSavePurchasematerial", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSavePurchasematerial(@RequestBody String purchasematerialJson) {
		Purchasematerial purchasematerial = new Gson().fromJson(purchasematerialJson, Purchasematerial.class);
		appendReferences(purchasematerial);
		CmiPsonService cmiPsonService = new CmiPsonService();
		purchasematerialService.savePurchasematerial(purchasematerial);
		return JSONObject.parse(cmiPsonService
				.toJsonString(purchasematerialDAO.findPurchasematerialByPrimaryKey(purchasematerial.getId()), 1));
	}

	@RequestMapping(value = "/restDeletePurchasematerial/{purchasematerialId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeletePurchasematerial(@PathVariable Integer purchasematerialId) {
		Purchasematerial purchasematerial = purchasematerialDAO.findPurchasematerialByPrimaryKey(purchasematerialId);
		purchasematerialService.deletePurchasematerial(purchasematerial);
	}

	@RequestMapping(value = "/restConfirmDeletePurchasematerials")
	@ResponseBody
	public Object restConfirmDeletePurchasematerials(@RequestBody Set<Integer> deletePurchasematerialsIds) {
		Set<Purchasematerial> deletePurchasematerials = purchasematerialDAO
				.findPurchasematerialsByIds(deletePurchasematerialsIds);
		Set<Purchasematerial> referencedPurchasematerials = purchasematerialService
				.loadReferencePurchasematerials(deletePurchasematerials);
		deletePurchasematerials.removeAll(referencedPurchasematerials);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedPurchasematerials);
		jsonObject.put("deleteEntitys", deletePurchasematerials);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeletePurchasematerials")
	@ResponseBody
	public Object restDeletePurchasematerials(@RequestBody Set<Purchasematerial> deletePurchasematerials) {
		Iterator<Purchasematerial> iterator = deletePurchasematerials.iterator();
		while (iterator.hasNext()) {
			Purchasematerial currentPurchasematerial = iterator.next();
			purchasematerialService.deletePurchasematerial(currentPurchasematerial);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listPurchasematerials");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadPurchasematerial/{purchasematerialId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadPurchasematerial(@PathVariable Integer purchasematerialId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(purchasematerialDAO.findPurchasematerialByPrimaryKey(purchasematerialId), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadPurchasematerialMaterial/{purchasematerialId}/material", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadPurchasematerialMaterial(@PathVariable Integer purchasematerialId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				purchasematerialDAO.findPurchasematerialByPrimaryKey(purchasematerialId).getMaterial(), 2,
				cmiPagination));
	}

	@RequestMapping(value = "/restLoadPurchasematerialProducer/{purchasematerialId}/producer", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadPurchasematerialProducer(@PathVariable Integer purchasematerialId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				purchasematerialDAO.findPurchasematerialByPrimaryKey(purchasematerialId).getProducer(), 2,
				cmiPagination));
	}

	@RequestMapping(value = "/restLoadPurchasematerialSupplier/{purchasematerialId}/supplier", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadPurchasematerialSupplier(@PathVariable Integer purchasematerialId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				purchasematerialDAO.findPurchasematerialByPrimaryKey(purchasematerialId).getSupplier(), 2,
				cmiPagination));
	}

	@RequestMapping(value = "/restLoadPurchasematerialUnit/{purchasematerialId}/unit", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadPurchasematerialUnit(@PathVariable Integer purchasematerialId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				purchasematerialDAO.findPurchasematerialByPrimaryKey(purchasematerialId).getUnit(), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	public void appendReferences(Purchasematerial purchasematerial) {

		Material material = purchasematerial.getMaterial();
		if (material != null)
			purchasematerial.setMaterial(materialService.findMaterialByPrimaryKey(material.getId()));

		Producer producer = purchasematerial.getProducer();
		if (producer != null)
			purchasematerial.setProducer(producerService.findProducerByPrimaryKey(producer.getId()));

		Supplier supplier = purchasematerial.getSupplier();
		if (supplier != null)
			purchasematerial.setSupplier(supplierService.findSupplierByPrimaryKey(supplier.getId()));

		Unit unit = purchasematerial.getUnit();
		if (unit != null)
			purchasematerial.setUnit(unitService.findUnitByPrimaryKey(unit.getId()));

	}

	@RequestMapping(value = "/restGetPurchasematerialMaterial/{purchasematerialId}/material", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetPurchasematerialMaterial(@PathVariable Integer purchasematerialId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				purchasematerialDAO.findPurchasematerialByPrimaryKey(purchasematerialId).getMaterial(), 2,
				cmiPagination));
	}

	@RequestMapping(value = "/restGetPurchasematerialProducer/{purchasematerialId}/producer", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetPurchasematerialProducer(@PathVariable Integer purchasematerialId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				purchasematerialDAO.findPurchasematerialByPrimaryKey(purchasematerialId).getProducer(), 2,
				cmiPagination));
	}

	@RequestMapping(value = "/restGetPurchasematerialSupplier/{purchasematerialId}/supplier", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetPurchasematerialSupplier(@PathVariable Integer purchasematerialId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				purchasematerialDAO.findPurchasematerialByPrimaryKey(purchasematerialId).getSupplier(), 2,
				cmiPagination));
	}

	@RequestMapping(value = "/restGetPurchasematerialUnit/{purchasematerialId}/unit", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetPurchasematerialUnit(@PathVariable Integer purchasematerialId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				purchasematerialDAO.findPurchasematerialByPrimaryKey(purchasematerialId).getUnit(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListPurchasematerials", method = RequestMethod.GET)
	@ResponseBody
	public Object restListPurchasematerials() {
		return JSONObject.parse(cmiPsonService.toJsonString(purchasematerialService.loadPurchasematerials(), 2));
	}

	@RequestMapping(value = "/restListPurchasematerialsPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListPurchasematerialsPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = purchasematerialPaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Purchasematerial> purchasematerials = purchasematerialDAO.findAllPurchasematerials(startResult,
				cmiPagination.getPaginationSize());
		String purchasematerialString = cmiPsonService.toPsonString(purchasematerials, 2, cmiPagination);

		return JSONObject.parse(purchasematerialString);
	}

	@RequestMapping("/purchasematerialSelectBox")
	@ResponseBody
	public JSONObject purchasematerialSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键
			case "Material":
				entitySet = materialService.loadMaterialsByIdSet(searchValue);
				break;
			case "Producer":
				entitySet = producerService.loadProducersByIdSet(searchValue);
				break;
			case "Supplier":
				entitySet = supplierService.loadSuppliersByIdSet(searchValue);
				break;
			case "Unit":
				entitySet = unitService.loadUnitsByIdSet(searchValue);
				break;

			// 被引用键
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键
			case "Material":
				entitySet = materialDAO.findAllMaterials((pageNumber - 1) * paginationSize, paginationSize);
				count = materialService.countMaterials();
				break;
			case "Producer":
				entitySet = producerDAO.findAllProducers((pageNumber - 1) * paginationSize, paginationSize);
				count = producerService.countProducers();
				break;
			case "Supplier":
				entitySet = supplierDAO.findAllSuppliers((pageNumber - 1) * paginationSize, paginationSize);
				count = supplierService.countSuppliers();
				break;
			case "Unit":
				entitySet = unitDAO.findAllUnits((pageNumber - 1) * paginationSize, paginationSize);
				count = unitService.countUnits();
				break;

			// 被引用键
			}
		} else {
			switch (selectItem) {
			// 外键
			case "Material":
				entitySet = materialDAO.findMaterialByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = materialService.countMaterialsByName(queryword);
				break;
			case "Producer":
				entitySet = producerDAO.findProducerByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = producerService.countProducersByName(queryword);
				break;
			case "Supplier":
				entitySet = supplierDAO.findSupplierByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = supplierService.countSuppliersByName(queryword);
				break;
			case "Unit":
				entitySet = unitDAO.findUnitByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = unitService.countUnitsByName(queryword);
				break;

			// 被引用键
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
